home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 4222 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.9 KB

  1. Path: airdmhor.gen.nz!not-for-mail
  2. From: gumboot@airdmhor.gen.nz (Simon Hosie)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: division problem
  5. Date: 3 Feb 1996 06:59:15 +1300
  6. Organization: Airdmhor
  7. Message-ID: <4etjdj$fil@airdmhor.gen.nz>
  8. References: <31097D77.11AA@rain.org> <26JAN199622082450@erich.triumf.ca> <4eh246$u6h@airdmhor.gen.nz> <4ej4ha$66@fountain.mindlink.net> <DLzvGG.2rn@uns.bris.ac.uk>  <Pine.SOL.3.90.960130150923.21923F-100000@flute>
  9. NNTP-Posting-Host: localhost.gen.nz
  10. X-Newsreader: TIN [version 1.2 PL2]
  11.  
  12. On Tue, 30 Jan 1996, Nathan Sidwell wrote:
  13. > Gene Wirchenko (genew@mindlink.bc.ca) wrote:
  14. > : gumboot@airdmhor.gen.nz (Simon Hosie) wrote:
  15. > : >celcius = (fahrenheit - 32) * 5 / 9;
  16. > :      That's disgusting <g> as it doesn't round.  Try it with 39 deg F:
  17. > :           (39-32)*5/9 ::= 7*5/9 ::= 35/9 ::= 3
  18. > : but the actual value is 3.8... i.e. nearly 4.  If you must int, 4
  19. > : would be a better answer.
  20. > Still no need to use floating point,
  21. > celcius = ((fahrenheit - 32) * 5 + 4) / 9
  22.  
  23. Darrell Grainger:
  24. > This ALMOST does the trick but 4/9 = 0.44444444... and 5/9 = 0.555555....
  25. > What you really want to do to eliminate the rounding errors is add 0.5 to
  26. > the number, e.g. 1.49999... + 0.5 = 1.9999... and (int)1.9999... = 1. So
  27. > 1.49999... rounds down to 1. Then 1.5 + 0.5 = 2.0 and (int)2.0 = 2. So
  28. > 1.5 rounds up to 2. This is what most people consider correct rounding.
  29.  
  30. > In your 'trick' you would have 1.5 + 0.4444... = 1.9444... and
  31. > (int)1.9444... = 1. This means that 1.5 rounds down to 1. This is not
  32. > proper. It is close but not proper. Alternatively, adding 5/9th would round
  33. > up certain numbers it should not.
  34.  
  35.   Hello?  Can anybody hear me?  Ok, let's try again...
  36.  
  37. #if -3 / 2 == -2
  38.     celcius = ((fahrenheit - 32) * 10 + 9) / 18;
  39. #else
  40.     celcius = ((fahrenheit - 32) * 10 + ((fahrenheit - 32 >= 0) ? 9 : -9)) 
  41.             / 18;
  42. #endif
  43.  
  44.   There.. complete, portable, accurate rounding.
  45.